<template>
  <div class="online-users-container">
    <!-- 页面标题区域 -->
    <div class="page-header-wrapper">
      <div class="page-title-section">
        <h1 class="page-title">在线用户管理</h1>
        <p class="page-description">实时监控在线用户状态，管理用户会话和分析使用统计</p>
      </div>
      <div class="page-actions-section">
        <button @click="getList" :disabled="loading" class="action-btn primary">
          <i class="fas fa-sync mr-2" :class="{ 'animate-spin': loading }"></i>
          <span>刷新数据</span>
        </button>
        <button @click="toggleStatsView" class="action-btn secondary">
          <i class="fas fa-chart-bar mr-2" v-if="!showStats"></i>
          <i class="fas fa-list mr-2" v-else></i>
          <span>{{ showStats ? '列表视图' : '统计视图' }}</span>
        </button>
      </div>
    </div>

    <!-- 统计概览卡片 -->
    <div class="stats-overview-section">
      <div class="stats-grid">
        <div class="stat-card">
          <div class="stat-content">
            <div class="stat-icon total">
              <i class="fas fa-users"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ detailStats?.totalCount || total || 0 }}</div>
              <div class="stat-label">在线用户总数</div>
            </div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-content">
            <div class="stat-icon active">
              <i class="fas fa-user-check"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ detailStats?.activeCount || 0 }}</div>
              <div class="stat-label">活跃用户</div>
              <div class="stat-desc">最近5分钟活动</div>
            </div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-content">
            <div class="stat-icon idle">
              <i class="fas fa-user-clock"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ detailStats?.idleCount || 0 }}</div>
              <div class="stat-label">空闲用户</div>
              <div class="stat-desc">超过5分钟无活动</div>
            </div>
          </div>
        </div>
        
        <div class="stat-card">
          <div class="stat-content">
            <div class="stat-icon sessions">
              <i class="fas fa-laptop"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ mySessions || 0 }}</div>
              <div class="stat-label">我的会话</div>
              <div class="stat-desc" v-if="detailStats?.averageOnlineMinutes">
                平均{{ (detailStats?.averageOnlineMinutes || 0).toFixed(1) }}分钟在线
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 图表分析区域 (仅在统计视图时显示) -->
    <div v-if="showStats && sessionDistribution" class="charts-section">
      <div class="charts-grid">
        <div class="chart-panel">
          <h3 class="chart-title">设备类型分布</h3>
          <div class="chart-container">
            <div class="chart-item" v-for="(item, key) in deviceData" :key="key">
              <div class="chart-label">{{ item.label }}</div>
              <div class="chart-bar">
                <div class="chart-progress" :style="{ width: item.percentage + '%' }"></div>
              </div>
              <div class="chart-value">{{ item.value }}</div>
            </div>
          </div>
        </div>
        
        <div class="chart-panel">
          <h3 class="chart-title">浏览器分布</h3>
          <div class="chart-container">
            <div class="chart-item" v-for="(item, key) in browserData" :key="key">
              <div class="chart-label">{{ item.label }}</div>
              <div class="chart-bar">
                <div class="chart-progress" :style="{ width: item.percentage + '%' }"></div>
              </div>
              <div class="chart-value">{{ item.value }}</div>
            </div>
          </div>
        </div>
        
        <div class="chart-panel">
          <h3 class="chart-title">登录时段分布</h3>
          <div class="chart-container">
            <div class="chart-item" v-for="(item, key) in timeData" :key="key">
              <div class="chart-label">{{ item.label }}</div>
              <div class="chart-bar">
                <div class="chart-progress" :style="{ width: item.percentage + '%' }"></div>
              </div>
              <div class="chart-value">{{ item.value }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 视图控制和用户列表 -->
    <div class="users-list-section">
      <div class="list-header">
        <h3 class="list-title">在线用户列表</h3>
        <div class="view-controls">
          <div class="view-scope-selector">
            <label>视图范围:</label>
            <div class="radio-group">
              <label class="radio-option" :class="{ active: viewScope === 'global' }">
                <input type="radio" v-model="viewScope" value="global" v-permission="'auth:session:all-list'" />
                <span>全局</span>
              </label>
              <label class="radio-option" :class="{ active: viewScope === 'tenant' }">
                <input type="radio" v-model="viewScope" value="tenant" v-permission="'auth:session:tenant-list'" />
                <span>租户</span>
              </label>
              <label class="radio-option" :class="{ active: viewScope === 'mine' }">
                <input type="radio" v-model="viewScope" value="mine" />
                <span>我的</span>
              </label>
            </div>
          </div>
        </div>
      </div>

      <div class="bg-panel radius-lg p-0">
        <el-table
          v-loading="loading"
          :data="onlineUserList"
          row-key="sessionId"
          border
          style="width: 100%"
        >
          <el-table-column prop="username" label="用户名" min-width="120" />
          <el-table-column prop="nickname" label="昵称" min-width="120" />
          <el-table-column prop="ip" label="IP地址" width="130" />
          <el-table-column prop="location" label="登录地点" min-width="150" />
          <el-table-column prop="browser" label="浏览器" min-width="120" />
          <el-table-column prop="os" label="操作系统" min-width="120" />
          <el-table-column prop="tenantId" label="租户" min-width="120" />
          <el-table-column prop="loginTime" label="登录时间" width="160" />
          <el-table-column prop="lastAccessTime" label="最后访问" width="160" />
          <el-table-column label="状态" width="100">
            <template #default>
              <el-tag type="success" size="small">在线</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center" fixed="right">
            <template #default="{ row }">
              <el-button
                type="danger"
                size="small"
                :icon="SwitchButton"
                @click="handleForceLogout(row)"
                v-permission="'auth:session:terminate'"
              >
                强退
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="d-flex justify-between items-center p-4">
          <el-pagination
            v-show="total > 0"
            :current-page="queryParams.current"
            :page-size="queryParams.size"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Refresh,
  SwitchButton,
  User
} from '@element-plus/icons-vue'
import type { OnlineUser } from '@/types/system'
import { authApi } from '@/api/auth'

// 响应式数据
const loading = ref(false)
const onlineUserList = ref<OnlineUser[]>([])
const total = ref(0)
const mySessions = ref(0)
const viewScope = ref<'global' | 'tenant' | 'mine'>('tenant')

const queryParams = reactive({
  current: 1,
  size: 20
})

// 方法
const getList = async () => {
  loading.value = true
  try {
    const countResp = await authApi.getOnlineUserCount()
    total.value = Number(countResp?.data ?? 0)

    // 根据选择的视图加载会话
    let sessionsResp: any
    if (viewScope.value === 'global') {
      sessionsResp = await authApi.getAllSessions({ limit: queryParams.size })
    } else if (viewScope.value === 'tenant') {
      sessionsResp = await authApi.getTenantSessions({ limit: queryParams.size })
    } else {
      sessionsResp = await authApi.getUserSessions()
    }
    const list: any[] = Array.isArray(sessionsResp?.data) ? sessionsResp.data as any[] : []
    // 🔧 适配新的SessionInfo字段名
    onlineUserList.value = list.map((s: any) => ({
      sessionId: s.sessionId,
      userId: s.userId,
      username: s.username || s.userId || '-',
      nickname: s.nickname || '-',
      deptName: s.deptName || '-',
      ip: s.clientIp || '-',                    // ✅ 使用新字段名
      location: s.loginLocation || '-',
      browser: s.userAgent || s.deviceInfo || '-',  // ✅ 使用新字段名
      os: s.osInfo || '-',
      loginTime: s.createTime || '-',           // ✅ 使用新字段名
      lastAccessTime: s.lastActiveTime || '-',  // ✅ 使用新字段名
      tenantId: s.tenantId,
      deviceInfo: s.deviceInfo,
      sessionDurationMinutes: s.sessionDurationMinutes,
      inactive: s.inactive,
      deviceType: s.deviceType,
      sessionActive: s.sessionActive
    }))
    // 刷新统计
    total.value = onlineUserList.value.length
    // 计算我的会话数量（按 userId == 当前登录用户）
    try {
      const me = JSON.parse(localStorage.getItem('kexio-user-info') || '{}')
      const myId = me?.userId
      mySessions.value = myId ? onlineUserList.value.filter(x => x.userId === myId).length : 0
    } catch {}
  } catch (error) {
    ElMessage.error('获取在线用户失败')
  } finally {
    loading.value = false
  }
}

const handleSizeChange = (size: number) => {
  queryParams.size = size
  getList()
}

const handleCurrentChange = (current: number) => {
  queryParams.current = current
  getList()
}

const handleForceLogout = async (row: OnlineUser) => {
  try {
    await ElMessageBox.confirm(
      `确定要强制用户"${row.username}"下线吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await authApi.terminateSession(row.sessionId)
    ElMessage.success('强制下线成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('强制下线失败')
    }
  }
}

// 生命周期
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped></style>
